<template>
  <div class="login-container">
    <div class="login-box">
      <!-- 后端状态指示器 -->
      <div class="server-status" :class="{ online: serverOnline, offline: !serverOnline }">
        {{ serverOnline ? '✅ 后端服务在线' : '❌ 后端服务离线（使用模拟数据）' }}
      </div>

      <h2>Easy Go 后台登录</h2>

      <!-- 登录表单 -->
      <form @submit.prevent="handleLogin" class="login-form" v-if="!showRegister">
        <div class="form-group">
          <label>用户名：</label>
          <input
              type="text"
              v-model="loginForm.username"
              placeholder="请输入用户名"
              required
              :disabled="isLoading"
          >
        </div>
        <div class="form-group">
          <label>密码：</label>
          <input
              type="password"
              v-model="loginForm.password"
              placeholder="请输入密码"
              required
              :disabled="isLoading"
          >
        </div>

        <div v-if="loginError" class="error-message">
          {{ loginError }}
        </div>

        <button type="submit" class="login-btn" :disabled="isLoading">
          {{ isLoading ? '登录中...' : '登录' }}
        </button>

        <div class="switch-form">
          <span>没有账号？</span>
          <a href="#" @click.prevent="showRegister = true">立即注册</a>
        </div>

        <div class="demo-accounts">
          <h4>测试账号：</h4>
          <p>admin / 123456</p>
        </div>
      </form>

      <!-- 注册表单 -->
      <form @submit.prevent="handleRegister" class="register-form" v-else>
        <h3>用户注册</h3>

        <div class="form-group">
          <label>用户名：</label>
          <input
              type="text"
              v-model="registerForm.username"
              placeholder="请输入用户名（至少3位）"
              required
              :disabled="isLoading"
          >
        </div>
        <div class="form-group">
          <label>密码：</label>
          <input
              type="password"
              v-model="registerForm.password"
              placeholder="请输入密码（至少6位）"
              required
              :disabled="isLoading"
          >
        </div>
        <div class="form-group">
          <label>确认密码：</label>
          <input
              type="password"
              v-model="registerForm.confirmPassword"
              placeholder="请再次输入密码"
              required
              :disabled="isLoading"
          >
        </div>
        <div class="form-group">
          <label>邮箱（可选）：</label>
          <input
              type="email"
              v-model="registerForm.email"
              placeholder="请输入邮箱地址"
              :disabled="isLoading"
          >
        </div>

        <div v-if="registerError" class="error-message">
          {{ registerError }}
        </div>

        <div v-if="registerSuccess" class="success-message">
          注册成功！正在自动登录...
        </div>

        <div class="button-group">
          <button type="submit" class="register-btn" :disabled="isLoading">
            {{ isLoading ? '注册中...' : '注册' }}
          </button>
          <button type="button" class="cancel-btn" @click="cancelRegister" :disabled="isLoading">
            取消
          </button>
        </div>

        <div class="switch-form">
          <span>已有账号？</span>
          <a href="#" @click.prevent="showRegister = false">立即登录</a>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

// 状态管理
const showRegister = ref(false)
const isLoading = ref(false)
const loginError = ref('')
const registerError = ref('')
const registerSuccess = ref(false)
const serverOnline = ref(false)

// 表单数据
const loginForm = reactive({
  username: '',
  password: ''
})

const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  email: ''
})

// 检查后端服务状态
const checkServerStatus = async () => {
  try {
    const response = await fetch('http://localhost:3000/api/health')
    serverOnline.value = response.ok
  } catch (error) {
    serverOnline.value = false
  }
}

// 登录处理
const handleLogin = async () => {
  loginError.value = ''
  isLoading.value = true

  try {
    if (!loginForm.username || !loginForm.password) {
      throw new Error('请输入用户名和密码')
    }

    await userStore.login(loginForm.username, loginForm.password)
    router.push('/dashboard')
  } catch (error: any) {
    loginError.value = error.message
  } finally {
    isLoading.value = false
  }
}

// 注册处理
const handleRegister = async () => {
  registerError.value = ''
  registerSuccess.value = false
  isLoading.value = true

  try {
    // 表单验证
    if (!registerForm.username || !registerForm.password) {
      throw new Error('请输入用户名和密码')
    }

    if (registerForm.username.length < 3) {
      throw new Error('用户名至少3位字符')
    }

    if (registerForm.password.length < 6) {
      throw new Error('密码至少6位字符')
    }

    if (registerForm.password !== registerForm.confirmPassword) {
      throw new Error('两次输入的密码不一致')
    }

    // 调用注册接口
    if (serverOnline.value) {
      const response = await fetch('http://localhost:3000/api/register', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          username: registerForm.username,
          password: registerForm.password,
          email: registerForm.email
        })
      })

      const data = await response.json()

      if (!response.ok) {
        throw new Error(data.error || '注册失败')
      }

      // 注册成功后自动登录
      userStore.currentUser = data.user
      userStore.token = data.token
      localStorage.setItem('currentUser', JSON.stringify(data.user))
      localStorage.setItem('token', data.token)
    } else {
      // 后端离线时使用前端模拟注册
      const newUser = {
        id: Date.now(),
        username: registerForm.username,
        email: registerForm.email || ''
      }

      userStore.currentUser = newUser
      userStore.token = 'demo-token-' + Date.now()
      localStorage.setItem('currentUser', JSON.stringify(newUser))
      localStorage.setItem('token', userStore.token)
    }

    // 注册成功
    registerSuccess.value = true
    registerError.value = ''

    // 2秒后自动跳转到仪表板
    setTimeout(() => {
      router.push('/dashboard')
    }, 2000)

  } catch (error: any) {
    registerError.value = error.message
  } finally {
    isLoading.value = false
  }
}

// 取消注册
const cancelRegister = () => {
  showRegister.value = false
  registerForm.username = ''
  registerForm.password = ''
  registerForm.confirmPassword = ''
  registerForm.email = ''
  registerError.value = ''
  registerSuccess.value = false
}

// 页面加载时检查登录状态 - 这里添加自动跳转逻辑
onMounted(async () => {
  await checkServerStatus()

  // 如果已登录，直接跳转到仪表板
  const token = localStorage.getItem('token')
  if (token) {
    router.push('/dashboard')
  }
})
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-box {
  background: white;
  padding: 40px;
  border-radius: 10px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  width: 100%;
  max-width: 450px;
}

.server-status {
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 20px;
  text-align: center;
  font-size: 14px;
  font-weight: bold;
}

.server-status.online {
  background: #f6ffed;
  border: 1px solid #b7eb8f;
  color: #389e0d;
}

.server-status.offline {
  background: #fff2f0;
  border: 1px solid #ffccc7;
  color: #a8071a;
}

h2, h3 {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

h3 {
  color: #667eea;
}

.form-group {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #555;
}

input {
  width: 100%;
  padding: 12px 15px;
  border: 2px solid #e1e5e9;
  border-radius: 6px;
  font-size: 16px;
  transition: border-color 0.3s;
}

input:focus {
  outline: none;
  border-color: #667eea;
}

input:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.login-btn, .register-btn, .cancel-btn {
  width: 100%;
  padding: 12px;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.login-btn, .register-btn {
  background: #667eea;
  color: white;
}

.login-btn:hover:not(:disabled), .register-btn:hover:not(:disabled) {
  background: #5a6fd8;
  transform: translateY(-1px);
}

.cancel-btn {
  background: #6c757d;
  color: white;
}

.cancel-btn:hover:not(:disabled) {
  background: #5a6268;
}

.button-group {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.button-group button {
  flex: 1;
}

.error-message {
  background: #fff2f0;
  border: 1px solid #ffccc7;
  color: #a8071a;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 15px;
  font-size: 14px;
}

.success-message {
  background: #f6ffed;
  border: 1px solid #b7eb8f;
  color: #389e0d;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 15px;
  font-size: 14px;
}

.switch-form {
  text-align: center;
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.switch-form a {
  color: #667eea;
  text-decoration: none;
  font-weight: 600;
}

.switch-form a:hover {
  text-decoration: underline;
}

.demo-accounts {
  margin-top: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
  font-size: 14px;
}

.demo-accounts h4 {
  margin: 0 0 10px 0;
  color: #666;
}

.demo-accounts p {
  margin: 5px 0;
  color: #888;
  font-family: monospace;
}

button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none !important;
}
</style>